const os = require('os');
const UAParser = require("ua-parser-js");
const request = require('request');
const db = require('../models');

/**
 * 免费获取ip地址 - 接口
 * https://searchplugin.csdn.net/api/v1/ip/get?ip=0.0.0.0
 * https://whois.pconline.com.cn/ipJson.jsp?json=true&ip=0.0.0.0
 * https://www.ip.cn/api/index?type=0&ip=0.0.0.0
 * https://api.vore.top/api/IPdata?ip=0.0.0.0
 * http://demo.ip-api.com/json/0.0.0.0?fields=61439&lang=zh-CN
 * https://opendata.baidu.com/api.php?co=&resource_id=6006&oe=utf8&query=0.0.0.0
 */


module.exports = function (req) {
    return new Promise((resolve, reject) => {
        const u = new UAParser(req.headers['user-agent'])
        try {
            let data = {
                ip: req.ip ?? '0.0.0.0',
                browser: u.getBrowser().name + '.v' + u.getBrowser().major,
                address: "解析异常",
                system: os.type() + os.release() + ' ' + os.arch(),
            }
            const headers = req.headers;
            if (headers['x-real-ip']) {
                data.ip = headers['x-real-ip'];
            } else if (headers['x-forwarded-for']) {
                const ipList = headers['x-forwarded-for'].split(',');
                data.ip = ipList[0];
            } else if (req.connection.remoteAddress) {
                data.ip = req.connection.remoteAddress
            }
            if (data.ip && data.ip != '0.0.0.0' && data.ip.indexOf('127.0.0.1') == -1) {
                // 先看缓存是否存在地址
                db.redis.get(`${data.ip}:address`, (err, string) => {
                    if (err || !string) {
                        // 获取ip和解析地址
                        request(`https://searchplugin.csdn.net/api/v1/ip/get?ip=${data.ip}`, { method: 'GET' },
                            function (error, response, body) {
                                try {
                                    if (error || !body) return resolve(data)
                                    data.address = JSON.parse(body).code === 200 ? JSON.parse(body).data.address : "解析异常"
                                    if (data.address != '解析异常') {
                                        // 缓存地址 3小时
                                        db.redis.setex(`${data.ip}:address`, 3 * 3600, data.address);
                                    }
                                    return resolve(data)
                                } catch (e) {
                                    return resolve(data)
                                }
                            })
                    } else {
                        data.address = string
                        db.redis.setex(`${data.ip}:address`, 3 * 3600, string);
                        return resolve(data)
                    }
                })
            } else {
                return resolve(data)
            }
        } catch (e) {
            resolve(data)
        }

    })

}

